<template>
  <div class="main">
    <transition name="change" mode="out-in">
      <div class="empty" v-if="datas.length < 1">
        <h3 class="empty-title">支持以下网站的新闻详情：</h3>
        <!-- <p class="empty-des">本扩展程序支持以下网站的新闻详情：</p> -->
        <ul class="sites">
          <li class="sites-item" v-for="(item, index) in sites" :key="index" @click="linkToSite(item)">
            <div class="sites-item-icon">
              <img :src="item.icon" />
            </div>
            <p class="sites-item-title">{{ item.title }}</p>
          </li>
        </ul>
      </div>
      <ul class="news" v-else>
        <transition-group name="list"> 
          <li class="new" v-for="(item, index) in datas" :key="item.url" @click="linkToNew(item)">
            <div class="new-icon">
              <img :src="item.favIconUrl" />
            </div>
            <p class="new-title">{{ item.title }}</p>
            <div class="new-status">
            </div>
            <div class="new-actions">
              <el-tooltip placement="top" effect="light" show-after="800" content="下载资源">
                <i class="iconfont new-action-icon icon-xiazai3 f_g" @click.self.stop="downloadNew(item)"></i>
              </el-tooltip>
              <el-tooltip placement="top" effect="light" show-after="800" content="编辑新闻">
                <!-- <i class="iconfont new-action-icon icon-a-shezhi-shucaidanshezhi-copy" @click.self.stop="editorNew(item)"></i> -->
                <i class="iconfont new-action-icon icon-a-shezhi-shucaidanshezhi-copy" @click.self.stop="sendRequest(item)"></i>
              </el-tooltip>
              <el-tooltip placement="top" effect="light" show-after="800" content="清除新闻">
                <i class="iconfont icon-dingdanzhuangtaishibai new-action-icon f_r" @click.self.stop="removeNew(item, index)"></i>
              </el-tooltip>
              
            </div>
            
          </li>
        </transition-group>
      </ul>
    </transition>
    
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { imageTest } from '@/api/image.js';
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import axios from 'axios';
import request from '@/utils/request.js';
console.log('chrome')
console.log(chrome)
// 已获取信息的新闻数据
const datas = ref([]);

// 展示的可采集的新网网站列表
const sites = ref([
  { title: '腾讯网', icon: '/icons/tencent.ico', url: 'https://www.qq.com/' },
  { title: '凤凰网', icon: '/icons/ifeng.ico', url: 'https://news.ifeng.com/' },
  { title: '今日头条', icon: '/icons/toutiao.ico', url: 'https://www.toutiao.com/' }
]);

// ============> utils
function getFileData(fileUrl){
  return new Promise((resolve, reject) => {
    axios(fileUrl, {
      method: 'GET',
      responseType: 'blob',
    })
      .then(res => {
        console.log(res)
        resolve(res);
      })
      .catch(error => {
        reject(error);
      })
  })
}
function handleImgs(arr){
  let result = [];
  arr.forEach((src, index) => {
    result.push({
      url: src,
      filename: index+1,
      type: 'image'
    })
  });
  return result;
}
function handleVideos(arr){
  // let result = [];
  // arr.forEach((src, index) => {
  //   result.push({
  //     url: src,
  //     filename: index+1,
  //     type: 'video'
  //   })
  // });
  // return result;
  let result = [];
  arr.forEach((item, index) => {
    if (typeof item === 'string'){
      result.push({
        url: item,
        filename: index + 1,
        type: 'video'
      });
    } else if (item && typeof item === 'object'){
      item.urls.forEach((src, ind) => {
        result.push({
          url: src,
          filename: `${item.title}${ind}`,
          type: 'videoTS'
        });
      });
    }
  });
  return result;
}

// ============> methods
// 点击支持的网站跳转到对应的新闻页
async function linkToSite(site){
  console.log(site);
  let result = await chrome.tabs.query({
    url: site.url
  });
  if (Array.isArray(result) && result.length > 0){
    !result[0].active && chrome.tabs.update(result[0].id, { active: true });
  } else {
    chrome.tabs.create({ url: site.url });
  }
}
// 下载新闻资源
function downloadNew(item){
  console.log(item);
  let texts = [];
  if (item.datas.text && item.datas.text.trim()){
    // 这里最后要释放掉
    let textBlobUrl =  URL.createObjectURL(new Blob([item.datas.text], { type: 'text/plain'}));
    let text = {
      filename: `${item.title}.txt`,
      url: textBlobUrl,
      type: 'text'
    };
    texts.push(text);
  }
  let imgs = handleImgs(item.datas.image || []);
  let videos = handleVideos(item.datas.video);
  const promises = [];
  const zip = new JSZip();
  [...imgs, ...videos, ...texts ].forEach(material => {
    const promiseItem = getFileData(material.url)
      .then(res => {
        console.log(res);
        let filename;
        if (material.type === 'text'){
          filename = material.filename;
        } else if (material.type === 'videoTS') {
          filename = `${material.filename}.ts`;
        } else {
          filename = `${material.filename}.${res.data.type.slice(res.data.type.indexOf('/') + 1)}`;
        }
        console.log(filename);
        zip.file(filename, res.data, { binary: true });
        material.type === 'text' && URL.revokeObjectURL(material.url);
      })
    promises.push(promiseItem);
  });
  Promise.all(promises)
    .then(() => {
      zip.generateAsync({
        type: 'blob',
        compression: 'DEFLATE',
        compressionOptions: {
          level: 9         
        }
      })
        .then(res => {
          FileSaver.saveAs(res, `${item.title}.zip`)
        })
        .catch(err => {
          console.log('下载失败：');
          console.log(err);
        })
    })
    .catch(err => {
      console.log('PromiseAll fail')
      console.log(err)
      ElMessage.error('获取新闻媒体资源失败，资源已过期请重新获取');
    })
}

// 点击编辑新闻跳转到外部项目
function editorNew(item){
  console.log(item);
  // 跳到指定的其他平台页面
  // chrome.tabs.create({ url: `http://192.168.103.108:80/extension/task?key=${encodeURIComponent(item.url)}`});
  // 尝试发送给算法后端跑算法请求
  // axios('http://10.26.2.248:50000/login', {
  //   method: 'POST',
  //   data: {
  //     username: 'admin',
  //     password: 'admin123'
  //   }
  // })
  //   .then(res => {
  //     console.log(res);
  //   })
  //   .catch(error => {
  //     console.log(error)
  //   });
  request({
    url: '/login',
    method: 'post',
    data: {
      username: 'admin',
      password: 'admin123'
    }
  })
    .then(res => {
      console.log('测试请求')
      console.log(res);
    })
    .catch(err => {
      console.log(err)
    })
}

// 测试接口(替换编辑按钮)
function sendRequest(item){
  console.log(item);
  let data = {
    token: 'web-chrome-extension',
    image_dir: []
  };
  if (item.datas.image && Array.isArray(item.datas.image) && item.datas.image.length > 0){
    data.image_dir = item.datas.image;
    console.log('请求参数');
    console.log(data)
    imageTest({
      url: '/run_DRCT',
      method: 'post',
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      data
    })
      .then(res => {
        console.log('请求结果');
        console.log(res)
      })
      .catch(err => {
        console.log(err)
      })
  }

}

// 删除新闻
async function removeNew(item, index){
  let keyInfo = await chrome.storage.local.get(item.url);
  if (keyInfo[item.url]){
    chrome.storage.local.remove(item.url, () => {
      datas.value.splice(index, 1);
      ElMessage.success('删除新闻成功');
    });
  }
}
// 跳转到指定新闻页
async function linkToNew(item){
  console.log(item);
  let result = await chrome.tabs.query({
    url: item.url
  });
  if (Array.isArray(result) && result.length > 0){
    !result[0].active && chrome.tabs.update(result[0].id, { active: true });
  } else {
    chrome.tabs.create({ url: item.url });
  }
}
// 初始化 - 获取新闻列表
async function init(){
  let localStorageKeys;
  if (chrome.storage.local.getKeys) {
    localStorageKeys = await chrome.storage.local.getKeys();
  } else {
    // console.log(await chrome.storage.local.get())
    let res = await chrome.storage.local.get();
    console.log(res)
    localStorageKeys = Object.keys(res);
  }
  if (Array.isArray(localStorageKeys) && localStorageKeys.length > 0){
    localStorageKeys.forEach(async (key) => {
      if (key.startsWith('http')){
        let keyInfo = await chrome.storage.local.get(key);
        console.log(keyInfo);
        datas.value.push(keyInfo[key]);
      }
    })
  }
}

onMounted(async () => {
  init();
})

</script>
<style lang="scss" scoped >
@import '@/assets/styles/mixin.scss';
.main {
  border: 1px solid #ccc;
  padding: 15px 10px;
  font-size: 14px;
  color: #c0c0c0;
  @include inset-shadow;
}
.empty-title {
  // color: #101010;
  color: silver;
  font-size: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
}

.sites {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.sites-item {
  width: calc(50% - 16px);
  display: flex;
  align-items: center;
  margin: 5px 0;
  padding: 8px;
  cursor: pointer;
  .sites-item-icon {
    width: 30px;
    height: 30px;
    margin-right: 20px;
    img {
      width: 100%;
      height: 100%;
      transition: all .3s linear;
    }
  }
  .sites-item-title {
    color: #111111;
    transition: all .3s linear;
  }
  &:hover {
    border-radius: 8px;
    background-color: rgb(51, 119, 255);
    .sites-item-icon img {
      transform: scale(1.1);
    }
    .sites-item-title {
      color: #fff;
      text-shadow: 0 2px 6px rgba(0, 0, 0, .5);
    }
  }
}

.news {
  width: 100%;
}
.new {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: space-around;
  border: 1px solid #ccc;
  border-radius: 6px;
  background-color: rgba(51, 119, 255, .5);
  margin: 10px 0;
  cursor: pointer;
  color: #fff;
  transition: all .3s linear;
  &:hover {
    background-color: rgb(51, 119, 255);
    box-shadow: 0 2px 6px 0 rgba(0, 0, 0, .4);
    .new-title {
      text-shadow: 0 2px 6px rgba(0, 0, 0, .5);
    }
  }
  .new-icon {
    width: 25px;
    height: 25px;
    // margin-right: 20px;
    margin: 0 6px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .new-title {
    width: calc(60% - 45px);
    overflow: hidden;
    // white-space: nowrap;
    // text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    // height: 100%;
    transition: all .3s linear;
  }
  .new-status {
    height: 30px;
    width: 60px;
    border: 1px solid #ccc;
    border-radius: 8px;
    box-shadow: inset 0 0 4px #ccc;
    background-color: #fff;
    display: flex;
    align-items: center;
  }
  .new-actions {
    .new-action-icon {
      text-shadow: 0 2px 4px rgba(0, 0, 0, .5);
      margin: 0 5px;
    }
  }
  
}
</style>
